package cn.hallele.leinsteining.ms.support.starter.components.plugin.config;

import cn.hallele.leinsteining.ms.infrastructure.plugin.captcha.client.CaptchaClient;
import cn.hallele.leinsteining.ms.infrastructure.plugin.captcha.properties.CaptchaProperties;
import cn.hallele.leinsteining.ms.infrastructure.plugin.safety.encoder.RSAPasswordEncoder;
import cn.hallele.leinsteining.ms.support.starter.components.plugin.properties.PluginProperties;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * PluginConfig
 *
 * @author anle5
 * @since 2024/7/28 15:13
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({PluginProperties.class})
public class PluginConfig {
    /**
     * 验证码操作客户端
     *
     * @param properties properties
     * @return CaptchaClient
     */
    @Bean
    public CaptchaClient captchaClient(PluginProperties properties, CodeGenerator codeGenerator) {
        return new CaptchaClient(codeGenerator, properties.getCaptcha());
    }

    /**
     * CodeGenerator
     *
     * @param properties properties
     * @return CodeGenerator
     */
    @Bean
    public CodeGenerator codeGenerator(PluginProperties properties) {
        CaptchaProperties.CodeProperties code = properties.getCaptcha().getCode();
        return switch (code.getType()) {
            case MATH -> new MathGenerator(code.getLength());
            case RANDOM -> new RandomGenerator(code.getLength());
        };
    }

    /**
     * 系统统一的加解密工具,带解密
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    public PasswordEncoder passwordEncoder(PluginProperties properties) {
        PluginProperties.PasswordEncodeProperties passwordEncoderProperties = properties.getPasswordEncoder();
        return new RSAPasswordEncoder(passwordEncoderProperties.getPubKey(), passwordEncoderProperties.getPriKey());
    }
}
